package com.baizhi.action;

import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class UserAction {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void login() throws IOException {
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);

        HttpServletResponse resp = ServletActionContext.getResponse();
        resp.setCharacterEncoding("utf-8");
        PrintWriter pw = resp.getWriter();

        Map<String, Object> map = new HashMap<>();
        if(user == null){
            //登录失败
            map.put("status", "failed");
            map.put("msg", "用户名或密码错误");
        }else{
            //登录成功
            map.put("status", "success");
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String mapJson = objectMapper.writeValueAsString(map);

        pw.print(mapJson);
        pw.flush();

    }
}
